<script context="module">
  export async function preload(page, session) {
    if (!session.user) {
      this.error(403, "对不起，请登录之后再查看本页面！");
      return;
    }
    if (!session.user.isadmin) {
      this.error(403, "对不起，只有管理员账号有权查看本页面！");
      return;
    }
    let { p } = page.query;
    if (!p) {
      p = 1;
    }
    p = parseInt(p);
    const perPage = 24;
    const response = await Promise.all([
      this.fetch(`/api2/user?page=${p}&limit=${perPage}`),
    ]);
    const users = await response[0].json();
    return { users: users.users, counts: users.counts, p, perPage };
  }
</script>

<script>
  import { goto, stores } from "@sapper/app";
  import dayjs from "dayjs";
  import relativeTime from "dayjs/plugin/relativeTime";
  import "dayjs/locale/zh-cn";
  import Pagination from "../../components/Pagination.svelte";
  import { toast } from "@zerodevx/svelte-toast";
  import {
    Modal,
    ModalBody,
    ModalFooter,
    ModalHeader
  } from 'sveltestrap/src';
  let open = false;
  const toggle = () => (open = !open);
  let pwdOpen = false;
  const pwdToggole = () => (pwdOpen = !pwdOpen);
  dayjs.extend(relativeTime);
  dayjs.locale("zh-cn");
  const { preloading, page, session } = stores();
  let path;
  let selectObj;
  let newPassword = '';
  $: path = $page.path;
  export let users;
  export let perPage;
  export let counts;
  export let p;
  async function changePage(evt) {
    const current = evt.detail;
    goto("/users?p=" + current);
  }
  async function deleteObj(id) {
    const response = await fetch("/api2/user?id=" + id, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
    });
    const parsed = await response.json();
    if (parsed.success == 0) {
      toast.push(parsed.message);
    } else {
      toast.push("删除成功，有10分钟缓存，请稍候再查看列表！");
    }
  }
  function openEdit(obj) {
    selectObj= obj;
    open = !open;
  }
  function openChangePwd(obj) {
    selectObj = obj;
    pwdOpen = !pwdOpen;
  }
  async function savePwd() {
    const response = await fetch("/api2/changepwd", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        id: selectObj._id,
        password: newPassword,
      }),
    });
    const parsed = await response.json();
    if (parsed.success == 0) {
      toast.push(parsed.message);
    } else {
      newPassword = '';
      toast.push("修改密码成功！");
      pwdOpen=!pwdOpen;
    }
  }
  async function save() {
    const response = await fetch("/api2/user", {
      method: "PUT",
      headers: {
        "Content-Type": "application/json",
        Accept: "application/json",
      },
      body: JSON.stringify({
        id: selectObj._id,
        phone: selectObj.phone,
        name: selectObj.name,
      }),
    });
    const parsed = await response.json();
    if (parsed.success == 0) {
      toast.push(parsed.message);
    } else {
      toast.push("编辑成功，因为缓存，可能几分钟之后才能看见修改结果！");
      open=!open;
    }
  }
</script>

<svelte:head>
  <title>系统用户管理中心 - 记账中心</title>
</svelte:head>
<div class="content">
  <div class="row">
  </div>
  <div class="row mt-4">
    <table class="table table-hover">
      <thead>
        <tr>
          <th scope="col">姓名</th>
          <th scope="col">手机号</th>
          <th scope="col">是否管理员</th>
          <th scope="col">创建日期</th>
          <th scope="col">操作</th>
        </tr>
      </thead>
      <tbody>
        {#each users as user}
          <tr>
            <td>{user.name}</td>
            <td>{user.phone}</td>
            <td>{user.isadmin?'是':'否'}</td>
            <td>{dayjs().from(dayjs(user.meta.createAt))}</td>
            <td>
              <div class="btn-group" role="group">
                <button class="btn btn-primary" on:click="{()=>{openEdit(user)}}">编辑</button>
                <button class="btn btn-info" on:click="{()=>{openChangePwd(user)}}">修改密码</button>
                <button class="btn btn-danger" on:click="{()=>{deleteObj(user._id)}}">删除</button>
              </div>
            </td>
          </tr>
        {/each}
      </tbody>
    </table>
  </div>
  <div class="d-flex justify-content-center mb-4">
    <Pagination
      rounded
      bind:current={p}
      num_items={counts}
      {perPage}
      on:navigate={changePage}
    />
  </div>
  <Modal isOpen={pwdOpen} toggle={pwdToggole}>
    <ModalHeader toggle={pwdToggole}>修改密码</ModalHeader>
    <ModalBody>
      <div class="form-group row">
        <label class="col-sm-2 col-form-label" for="name">输入密码</label>
        <div class="col-sm-10">
          <input
            type="password"
            id="password"
            class="form-control"
            placeholder="输入新密码"
            bind:value={newPassword}
          />
        </div>
      </div>
    </ModalBody>
    <ModalFooter>
      <button class="btn btn-primary" on:click="{savePwd}">保存</button>
      <button class="btn btn-danger" on:click="{()=>{pwdOpen=!pwdOpen}}">关闭</button>
    </ModalFooter>
  </Modal>
  <Modal isOpen={open} {toggle}>
    <ModalHeader {toggle}>编辑用户</ModalHeader>
    <ModalBody>
      <div class="form-group row">
        <label class="col-sm-2 col-form-label" for="name">姓名</label>
        <div class="col-sm-10">
          <input
            type="text"
            id="name"
            class="form-control"
            placeholder="输入姓名"
            bind:value={selectObj.name}
          />
        </div>
      </div>
      <div class="form-group row">
        <label class="col-sm-2 col-form-label" for="phone">手机号</label>
        <div class="col-sm-10">
          <input
            type="text"
            id="phone"
            class="form-control"
            placeholder="输入手机号"
            bind:value={selectObj.phone}
          />
        </div>
      </div>
    </ModalBody>
    <ModalFooter>
      <button class="btn btn-primary" on:click="{save}">保存</button>
      <button class="btn btn-danger" on:click="{()=>{open=!open}}">关闭</button>
    </ModalFooter>
  </Modal>
</div>
